package com.modelclient.baselib.view;

import android.app.Activity;
import android.app.ActivityManager;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Color;
import android.graphics.Typeface;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.widget.EditText;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;

import com.gyf.barlibrary.ImmersionBar;
import com.modelclient.baselib.util.ActivityHook;
import com.modelclient.baselib.util.StatusBarUtil;
import com.modelclient.baselib.util.TUtil;
import com.modelclient.baselib.util.ToastUtil;
import com.modelclient.baselib.util.UtilActivity;
import com.modelclient.baselib.widget.ProgressDialog;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

/**
 * 作者：Hxm
 * 创建时间：2017/6/7 15:31
 * 功能说明：activty基类，提供一些公共方法，公共设置
 */

public class BaseActivity<T extends BasePresenter> extends AppCompatActivity {

    public Context mContext;
    public T mPresenter;
    protected final static String PAGE_SIZE = "20";
    private ProgressDialog progressDialog;

    protected boolean isActive = true;

    public float density;
    protected Typeface iconfont;
    public boolean isInterceptDoubleClick = true;
    /** 基类(Activity)所使用的TAG标签 */
    protected String TAG = null;
    /**
     * 扫码进入的code
     */
    private String qrcode;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        ActivityHook.hookOrientation(this);//hook，绕过检查
        super.onCreate(savedInstanceState);
        // 用于确定当前界面是属于哪个活动(Activity), 让新加入开发的人快速锁定所在的界面
        TAG = getClass().getSimpleName();
        Log.e("", TAG);
        // 将其子activity添加到activity采集器
        UtilActivity.addActivity(this);
        density = getResources().getDisplayMetrics().density;
//        iconfont = Typeface.createFromAsset(getAssets(), "fonts/iconfont.ttf");
        if (this instanceof FragmentHostActivity){
        }else {
            mPresenter = TUtil.getT(this, 0);
        }
        if (this instanceof BaseView) mPresenter.setVM(this);

        if (getSupportActionBar() != null) {
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        }

        mContext = this;
        progressDialog = new ProgressDialog(mContext);

        setFullScreenAndTransparent(this);
        setAndroidNativeLightStatusBar(true);
        StatusBarUtil.setStatusBarColor(getActivity(), Color.parseColor("#FFFFFF"));

        qrcode = getIntent().getStringExtra("qrcode");
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        // TODO Auto-generated method stub
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            // 判断连续点击事件时间差
            if (isFastClick() && isInterceptDoubleClick) {
                return true;
            }
        }
        return super.dispatchTouchEvent(ev);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    protected void onStop() {
        super.onStop();
        if (!isAppOnForeground()) {
            //app 进入后台
            isActive = false;
        }
    }

    @Override
    protected void onDestroy() {
        // 将其子activity从activity采集器中移除
        UtilActivity.removeActivity(this);
        ImmersionBar.with(this).destroy();
        if(mPresenter!=null){
            mPresenter.onDestroy();
            mPresenter = null;
        }
        super.onDestroy();
    }

    protected String getBundleString(@NonNull String name){
        Bundle bundle = getIntent().getExtras();
        if(bundle != null){
            return bundle.getString(name);
        }else {
            return "";
        }
    }

    protected void startActivitry(@NonNull Class clazz, String[][] val){
        Intent intent = new Intent(this,clazz);
        Bundle bundle = new Bundle();
        if(val!=null){
            for (String[] aVal : val) {
                bundle.putString(aVal[0], aVal[1]);
            }
            intent.putExtras(bundle);
        }
        startActivity(intent);
    }

    protected void startActivitryForResult(@NonNull Class clazz, String[][] val){
        Intent intent = new Intent(this,clazz);
        Bundle bundle = new Bundle();
        if(val!=null){
            for (String[] aVal : val) {
                bundle.putString(aVal[0], aVal[1]);
            }
            intent.putExtras(bundle);
        }
        startActivityForResult(intent,100);
    }

    /**
     * 同步cookie
     *
     * @param url 地址
     * @param cookieList 需要添加的Cookie值,以键值对的方式:key=value
     */
    private void syncCookie (String url, ArrayList<String> cookieList) {
        CookieSyncManager.createInstance(mContext);
        CookieManager cookieManager = CookieManager.getInstance();
        cookieManager.setAcceptCookie(true);
        if (cookieList != null && cookieList.size() > 0) {
            for (String cookie : cookieList) {
                cookieManager.setCookie(url, cookie);
            }
        }
        cookieManager.setCookie(url, "Domain=.xrkmall.com");
        String cookies = cookieManager.getCookie(url);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            cookieManager.flush();
        } else {
            CookieSyncManager.getInstance().sync();
        }
    }

    public void hideSoftInput(EditText et) {
        InputMethodManager inputManager = (InputMethodManager)et.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
        if ( inputManager.isActive( ) ) {
            inputManager.hideSoftInputFromWindow(et.getWindowToken(), 0);
        }
    }

    public void showSoftInput(EditText et) {
        et.setFocusable(true);
        et.setFocusableInTouchMode(true);
        et.requestFocus();

        InputMethodManager inputManager = (InputMethodManager)et.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
        inputManager.showSoftInput(et, 0);
    }

    public void showToast(String str){
        //Toast.makeText(mContext,str,Toast.LENGTH_SHORT).show();
        Toast toast = Toast.makeText(mContext,str, Toast.LENGTH_LONG);
        toast.setGravity(Gravity.CENTER, 0, 0);
        toast.show();
    }

    /**
     * 程序是否在前台运行
     *
     * @return
     */
    public boolean isAppOnForeground() {
        // Returns a list of application processes that are running on the
        // device

        ActivityManager activityManager = (ActivityManager) getApplicationContext().getSystemService(Context.ACTIVITY_SERVICE);
        String packageName = getApplicationContext().getPackageName();

        List<ActivityManager.RunningAppProcessInfo> appProcesses = activityManager
                .getRunningAppProcesses();
        if (appProcesses == null)
            return false;

        for (ActivityManager.RunningAppProcessInfo appProcess : appProcesses) {
            // The name of the process that this object is associated with.
            if (appProcess.processName.equals(packageName)
                    && appProcess.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
                return true;
            }
        }

        return false;
    }

    public Activity getActivity(){
        return this;
    }

    /** 参数传递(注：该方法为了方便传参,参数类型有局限性,传递特殊类型时单独构建Intent) **/
    public void goTo(Class<?> goToCls, Object... values) {
        goTo(false, goToCls, values);
    }

    // <editor-fold defaultstate="collapsed" desc="参数传递(注：该方法为了方便传参,参数类型有局限性,传递特殊类型时单独构建Intent)">
    public void goTo(boolean finish, Class<?> goToCls, Object... values) {
        Intent intent = new Intent(this, goToCls);
        int i = 0;
        for (Object value : values) {
            Class<?> cls = value.getClass();
            String key = String.valueOf(i);
            if (cls == String.class) {
                intent.putExtra(key, (String) value);
            } else if (value instanceof Serializable) {
                intent.putExtra(key, (Serializable) value);
            } else if (cls == int[].class) {
                intent.putExtra(key, (int[]) value);
            } else if (cls == long[].class) {
                intent.putExtra(key, (long[]) value);
            } else if (cls == boolean[].class) {
                intent.putExtra(key, (boolean[]) value);
            } else if (cls == float[].class) {
                intent.putExtra(key, (float[]) value);
            } else if (cls == double[].class) {
                intent.putExtra(key, (double[]) value);
            } else if (cls == char[].class) {
                intent.putExtra(key, (char[]) value);
            } else if (cls == String[].class) {
                intent.putExtra(key, (String[]) value);
            } else if (cls == Bundle.class) {
                intent.putExtra(key, (Bundle) value);
            } else {
                throw new RuntimeException("不支持参数类型: " + cls.getSimpleName());
            }
            i++;
        }
        startActivity(intent);
        if (finish) {
            finish();
        }
    }
    // </editor-fold>

    public static void VISIBLE(View view) {
        if (view != null) {
            view.setVisibility(View.VISIBLE);
        }
    }

    public static void INVISIBLE(View view) {
        if (view != null) {
            view.setVisibility(View.INVISIBLE);
        }
    }

    public static void GONE(View view) {
        if (view != null) {
            view.setVisibility(View.GONE);
        }
    }

    /** 显示Toast信息 **/
    public void T(Object s) {
        ToastUtil.showToast(String.valueOf(s));
    }


    /**
     * 设置状态栏颜色
     *
     * @param dark
     */
    public void setAndroidNativeLightStatusBar(boolean dark) {
        View decor = this.getWindow().getDecorView();
        if (dark) {
            decor.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
        } else {
            decor.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
        }
    }

    /**
     * 设置状态栏透明且全屏
     *
     * @param activity
     */
    public static void setFullScreenAndTransparent(Activity activity) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                //5.x开始需要把颜色设置透明，否则导航栏会呈现系统默认的浅灰色
                Window window = activity.getWindow();
                View decorView = window.getDecorView();
                //两个 flag 要结合使用，表示让应用的主体内容占用系统状态栏的空间
                int option = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE;
                decorView.setSystemUiVisibility(option);
                window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
                window.setStatusBarColor(Color.TRANSPARENT);
            } else {
                Window window = activity.getWindow();
                WindowManager.LayoutParams attributes = window.getAttributes();
                int flagTranslucentStatus = WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS;
                attributes.flags |= flagTranslucentStatus;
                window.setAttributes(attributes);
            }
        }
    }

//    @Override
//    protected void attachBaseContext(Context newBase) {
//        super.attachBaseContext(CalligraphyContextWrapper.wrap(newBase));
//    }


    public Resources getResources() {
        Resources resources = super.getResources();
        if (resources != null && resources.getConfiguration().fontScale != 1.0f) {
            android.content.res.Configuration configuration = resources.getConfiguration();
            configuration.fontScale = 1.0f;
            resources.updateConfiguration(configuration, resources.getDisplayMetrics());
        }
        return resources;
    }

    public void addFragmentNeedToStack(Fragment fragment){
        try {
            String tag = fragment.getClass().getName();
            getSupportFragmentManager().beginTransaction().add(Window.ID_ANDROID_CONTENT,fragment,tag).addToBackStack(tag).commit();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void show_progressDialog(){
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if(progressDialog != null){
                    progressDialog.show();
                }
            }
        });
    }

    public void dismiss_progressDialog(){
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if(progressDialog != null){
                    progressDialog.dismiss();
                }
            }
        });
    }


    private static final int MIN_DELAY_TIME = 300;  // 两次点击间隔不能少于300ms
    private static long lastClickTime;

    public static boolean isFastClick() {
        boolean flag = true;
        long currentClickTime = System.currentTimeMillis();
        if ((currentClickTime - lastClickTime) >= MIN_DELAY_TIME) {
            flag = false;
        }
        lastClickTime = currentClickTime;
        return flag;
    }
}
